//
//  WXComposeViewController.swift
//  weibo
//
//  Created by 王旭 on 16/4/25.
//  Copyright © 2016年 王旭. All rights reserved.


//微博发送界面控制器

import UIKit
import SVProgressHUD

class WXComposeViewController: UIViewController {
    override func viewDidLoad() {
       setupUI()
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        textView.becomeFirstResponder()
    }
    
//布局界面
    func setupUI() {
        view.backgroundColor = UIColor.whiteColor()

        setupNav()
        
        //添加控件
        view.addSubview(textView)
        view.addSubview(toolBar)
        textView.addSubview(pictureCollectionView)
        
        //约束
        textView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self.view)
        }
        toolBar.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.bottom.equalTo(self.view)
            make.height.equalTo(44)
        }
        pictureCollectionView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(100)
            make.leading.equalTo(10)
            make.width.equalTo(self.view).offset(-20)
            make.height.equalTo(pictureCollectionView.snp_width)
        }
        
        //通知监控键盘变化
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardFrameChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "emoticonDeleteButtonClick", name: WXEmoticonDeleteButtonClickNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "emoticonButtonClick:", name: WXEmoticonButtonClickNotification, object: nil)
        
    }
    
//设置导航条
    private func setupNav() {
        //添加导航条左侧按钮提供返回上个控制器
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "back")
        //设置titleView
        navigationItem.titleView = titleView
        //设置右侧按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton)
        navigationItem.rightBarButtonItem?.enabled = false
    }
    
// 删除按钮点击
    @objc private func emoticonDeleteButtonClick(){
        textView.deleteBackward()
    }
    
//发送微博按钮点击事件
    @objc func sendButtonClick() {
        
        //        var result = ""
        //
        //        let attr = textView.attributedText
        //        // 遍历富文本里面的内容
        //        attr.enumerateAttributesInRange(NSMakeRange(0, attr.length), options: []) { (dict, range, _) -> Void in
        ////            print(dict)
        ////            print("===================")
        //            if let atta = dict["NSAttachment"] as? HMTextAttachment {
        //                print(atta.emoticon?.chs)
        //                // 是表情，取到表情的描述字符串
        //                result += atta.emoticon?.chs ?? ""
        //            }else{
        //                // 不是表情，是文字 ，所以我们需要截取
        //                result += (attr.string as NSString).substringWithRange(range)
        //            }
        //        }
        //        print(result)
        
        if pictureCollectionView.hidden == false {
            upload()
        }else{
            update()
        }

    }

//发送文字微博
    private func update() {
        //1.请求地址https://api.weibo.com/2/statuses/update.json
        let requestStr = "https://api.weibo.com/2/statuses/update.json"
        //2.请求参数
        let prameters = [
            "access_token" : WXUserAccountViewModel.sharedUserAccountViewModel.accessToken ?? "",
//            "status" : textView.text!
            "status" : textView.emoticonText!
        ]
        //3.发送请求
        WXNetworkTools.sharedTools.request(.Post, urlString: requestStr, parameters: prameters) { (responseObject, error) -> () in
            if error != nil {
                SVProgressHUD.showErrorWithStatus("发送失败")
                return
            }
            SVProgressHUD.showInfoWithStatus("发送成功")
        }
    }
    
//发送带图微博
    private func upload() {
            //1.请求地址https://upload.api.weibo.com/2/statuses/upload.json
            let requestStr = "https://upload.api.weibo.com/2/statuses/upload.json"
            //2.请求参数
            let prameters = [
                "access_token" : WXUserAccountViewModel.sharedUserAccountViewModel.accessToken ?? "",
//                "status" : textView.text!
                "status" : textView.emoticonText!
            ]
            //3.发送请求 application/octet-stream
            let data = UIImagePNGRepresentation(self.pictureCollectionView.images.first!)!
        WXNetworkTools.sharedTools.upload(requestStr, prameters: prameters, datas: ["pic":data]) { (responseObject, error) -> () in
            if error != nil {
                print(error)
                SVProgressHUD.showErrorWithStatus("发送失败")
                return
            }
            SVProgressHUD.showInfoWithStatus("发送成功")
            
        }
    }
    
//--------------------以下为测试代码,抽取之前-----------------
//    //发送带图微博
//    private func upload() {
//        //1.请求地址https://upload.api.weibo.com/2/statuses/upload.json
//        let requestStr = "https://upload.api.weibo.com/2/statuses/upload.json"
//        //2.请求参数
//        let prameters = [
//            "access_token" : WXUserAccountViewModel.sharedUserAccountViewModel.accessToken ?? "",
//            "status" : textView.text!
//        ]
//        //3.发送请求 application/octet-stream
//        WXNetworkTools.sharedTools.POST(requestStr, parameters: prameters, constructingBodyWithBlock: { (formData) -> Void in
//            //把图片转为二进制数据-接口只能传一张图
//            let data = UIImagePNGRepresentation(self.pictureCollectionView.images.first!)
//            formData.appendPartWithFileData(data!, name: "pic", fileName: "图图", mimeType: "application/octet-stream")
//            }, progress: nil, success: { (_, respose) -> Void in
//                SVProgressHUD.showInfoWithStatus("发送成功")
//            }) { (_, error) -> Void in
//                SVProgressHUD.showErrorWithStatus("发送失败")
//        }
//    }
//--------------------以上为测试代码,抽取之前-----------------

    
    // MARK: - 监听事件
    @objc private func emoticonButtonClick(noti: NSNotification) {
        let emoticon = noti.userInfo!["emoticon"] as! WXEmotionModel
        print(emoticon.chs)
        
        // 判断是否是emoji表情
        if emoticon.type == "1" {
            // emoji表情
            textView.insertText((emoticon.code! as NSString).emoji())
        }else{
            print("图片表情点击哈哈")
            //            textView.attributedText
            
            textView.insertEmoticon(emoticon)
            
            // 以下代码抽取到了 UITextView+extension.swift 中
            //            // 1.  将现有文字生成一个 NSMutableAttributedString
            //            let originalAttr = NSMutableAttributedString(attributedString: textView.attributedText)
            //
            //            // 2. 通过表情模型生成表情图片 --> 通过图片生成 NSTextAttachment --> 通过 attachment 生成一个 NSAttributedString
            //            let image = UIImage(named: "\(emoticon.folderName ?? "")/\(emoticon.png ?? "")", inBundle: HMEmoticonKeyBoardViewModel.sharedViewModel.emoticonBundle, compatibleWithTraitCollection: nil)
            //            // 通过图片生成NSTextAttachment
            //            let attatchment = NSTextAttachment()
            //            attatchment.image = image
            //            // 设置图片的大小
            //            let attachmentHW = textView.font!.lineHeight
            //            attatchment.bounds = CGRect(x: 0, y: -4, width: attachmentHW, height: attachmentHW)
            //            // 通过 attachment 生成一个 NSAttributedString
            //            let attr = NSAttributedString(attachment: attatchment)
            //
            //            // 3. 将第2部生成的 NSAttributedString 添加到第1步生成的 NSMutableAttributedString 里面
            //            // 添加到原有富文本里面
            //            // 以方法会把图标拼接到原来的文本的最后面，如果光标不是在最后面的话，就会出现bug
            //            // originalAttr.appendAttributedString(attr)
            //
            //            // 获取光标所在的位置
            //            var selectedRange = textView.selectedRange
            //            // originalAttr.insertAttributedString(attr, atIndex: selectedRange.location)
            //            originalAttr.replaceCharactersInRange(selectedRange, withAttributedString: attr)
            //
            //            // 设置字体大小
            //            originalAttr.addAttribute(NSFontAttributeName, value: textView.font!, range: NSMakeRange(0, originalAttr.length))
            //            // 4. 将第3步的执行结果赋值给 textView.attributedText
            //            textView.attributedText = originalAttr
            //            // 设置光标位置
            //            selectedRange.location += 1
            //            selectedRange.length = 0
            //            textView.selectedRange = selectedRange
        }
    }
    
    
    
//返回按钮点击事件
    @objc private func back() {
        textView.resignFirstResponder()
//        textView.endEditing(true)
        dismissViewControllerAnimated(true, completion: nil)
    }
    
//键盘通知调用方法
    @objc private func keyBoardFrameChange(noti:NSNotification) {
        //1.获得键盘的Frame
        let endFrame = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
//        print(endFrame.self)
//        print(endFrame.origin.y - SCRREN_H)
        //2.更改ToolBar的Frame
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(endFrame.origin.y - SCRREN_H)
        }
        //3.更新控件
        UIView.animateWithDuration(0.5) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
//选择图片按钮调用方法
    private func PictureClick() {
        let vc = UIImagePickerController()
        //设置代理
        vc.delegate = self
        presentViewController(vc, animated: true, completion: nil)
    }
    
//表情或键盘按钮点击事件
    private func EmoticonClick() {
        //1.判断是否是系统键盘,切换
        textView.inputView = textView.inputView == nil ? keyBoardView : nil
        //2.把判断结果传给toolBar
        toolBar.isSystemKeyBoard = textView.inputView == nil
        //3.刷新视图
        textView.reloadInputViews()
        //设置第一响应者
        if textView != isFirstResponder() {
            textView.becomeFirstResponder()
        }
    }
    
//以下为懒加载----------------------------------------------

//懒加载自定义键盘视图
    private lazy var keyBoardView : WXKeyBoardView = {
        let keyBoardView = WXKeyBoardView()
        //--------------------以下为测试代码-----------------
        //        keyBoardView.frame.size = CGSize(width: SCREEN_W, height: 258)
        //--------------------以上为测试代码-----------------
        keyBoardView.frame.size = CGSize(width: SCREEN_W, height: 216)
        return keyBoardView
    }()

//懒加载collectionView
    //循环引用
    //1.pictureCollectionView->pictureCollectionCellClick
    //2.pictureCollectionCellClick->WXComposeViewController
    //3.WXComposeViewController->pictureCollectionView
    private lazy var pictureCollectionView : WXComposePictureCollectionView = {
      let pictureCollectionView = WXComposePictureCollectionView(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout())
        pictureCollectionView.pictureCollectionCellClick = {[weak self] in
            self?.PictureClick()
        }
        return pictureCollectionView
    }()
    
//懒加载底部toolBar
    //循环引用
    //1.toolBar->toolBarButtonClickClosure
    //2.toolBarButtonClickClosure->WXComposeViewController 解决:[weak self]
    //3.WXComposeViewController->toolBar
    private lazy var toolBar :WXComposeToolBar = {
        let toolBar = WXComposeToolBar(frame: CGRectZero)
        toolBar.toolBarButtonClickClosure = {[weak self] (type:ToolBarButtonType)->() in
            print(type)
            switch type{
            case .Picture:
                self?.PictureClick()
                break
            case .Mention:
                break
            case .Trend:
                break
            case .Emoticon:
                self?.EmoticonClick()
                break
            case .Add:
                break
            }
        }
        return toolBar
    }()

//懒加载textView
    private lazy var textView :WXTextView = {
        let textView = WXTextView()
        //设置代理
        textView.delegate = self
        textView.placeholder = "爽歪的麻雀,在电线杆上哆嗦"
        textView.font = UIFont.systemFontOfSize(16)
        return textView
    }()
    
    
//懒加载发送按钮
    private lazy var sendButton : UIButton = {
       let sendButton = UIButton()
        //点击事件
        sendButton.addTarget(self, action: "sendButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        //设置文字
        sendButton.setTitle("发送", forState: .Normal)
        //设置文字颜色
        sendButton.setTitleColor(UIColor.grayColor(), forState: .Disabled)
        //设置不同状态下的背景图片
        sendButton.setBackgroundImage(UIImage(named: "common_button_orange"), forState: UIControlState.Normal)
        sendButton.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: UIControlState.Highlighted)
        sendButton.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Disabled)
        //设置按钮大小
        sendButton.frame.size = CGSize(width: 45, height: 28)
        //--------------------以下为测试代码-----------------
//        //设置按钮的状态->没效果,需要设置barButtonItem
//        sendButton.enabled = false
        //--------------------以上为测试代码-----------------
        return sendButton
    }()
    
//懒加载中间的View
    private lazy var titleView :UILabel = {
        //实例化
        let titleView = UILabel(textColor: UIColor.blackColor(), fontSize: 16)
        //设置换行
        titleView.numberOfLines = 0
        //文字居中
        titleView.textAlignment = .Center
        //获得微博使用人的姓名
        if let name = WXUserAccountViewModel.sharedUserAccountViewModel.userAccount?.name {
            //存在姓名
           //获得name在text字符串中的位置
            let text = "发微博\n\(name)"
            let range = (text as NSString).rangeOfString(name)
            //设置文本属性
            let attributeStr = NSMutableAttributedString(string: text)
            attributeStr.addAttributes(
                [NSForegroundColorAttributeName:UIColor.lightGrayColor(),
                NSFontAttributeName:UIFont.systemFontOfSize(14),
                    NSStrokeColorAttributeName:UIColor.purpleColor(),
                    NSStrokeWidthAttributeName:1],
                range: range)
            //赋值给父文本
            titleView.attributedText = attributeStr
        }else{
            titleView.text = "发微博"
        }
        
        //设置label大小
        titleView.sizeToFit()
        
        return titleView
    }()
    
//以上为懒加载----------------------------------------------
    
    deinit{
        //移除通知
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

}


//textView的代理方法
extension WXComposeViewController:UITextViewDelegate,UINavigationControllerDelegate {
    func textViewDidChange(textView: UITextView) {
        sendButton.enabled = textView.hasText()
    }
}

//imagePickController的代理方法
extension WXComposeViewController:UIImagePickerControllerDelegate {
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        //压缩图片
        let img = image.scaleToWidth(600)
        
//--------------------以下为测试代码-----------------
//        //把图片转为二进制文件
//        let data = UIImagePNGRepresentation(img)
//        //保存到zhuomia
//        data?.writeToFile("/Users/wx/Desktop/555", atomically: true)
//--------------------以上为测试代码-----------------

        //把图片传给collectionView
        pictureCollectionView.addImage(img)
        //dismiss当前控制器
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
}
